package client.ui;

import client.network.BanchoClient;
import common.Callback;
import common.enums.RequestType;
import common.requests.Request;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class registerUIController implements Initializable,ControlledStage, Callback {
    stageController theStageController;

    private String userName;
    private String userPassword;
    private String espd;         //ensurepassword
    private boolean flag;        //正确填写所有信息flag为true

    @FXML
    private TextField userNameField;
    @FXML
    private PasswordField password;
    @FXML
    private Label tip;//密码旁标签提示
    @FXML
    private PasswordField ensure;
    @FXML
    private Label esLb;//确认密码旁标签提示

    @FXML private Button register;//注册按钮


    //实现接口函数
    public void setStageController(stageController stageController){ theStageController = stageController;}

    //非法时提示格式
    private void unValidFunction(Label label){
        label.setTextFill(Color.RED);
        label.setVisible(true);
        flag = false;
        register.setDisable(true);
    }

    //合法时提示格式
    private void  validFunction(Label label){
        label.setText("正确");
        label.setTextFill(Color.GREEN);
        flag = true;
        register.setDisable(false);
    }

    //输入昵称  失去焦点时保存
    @Override
    @FXML
    public void initialize(URL location, ResourceBundle resources) {
        //用户名
        userNameField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                if (!userNameField.isFocused()) {
                    userName = userNameField.getText().trim();
                }
            }
        });
    }

    //判断密码
    //链接password的keyType
    public void changeNowPassword(KeyEvent keyEvent) {
        userPassword = password.getText().trim() + keyEvent.getCharacter().trim();
        password.textProperty().addListener((observable, oldValue, newValue) -> {
                ensure.clear();
                unValidFunction(esLb);
                esLb.setText("请保持一致！");
        });

        //密码不为空
        if (userPassword == null || userPassword.length() == 0) {
            tip.setText("密码不为空！");
            unValidFunction(tip);
        }

        //不合法则显示密码不超过14位
        if (userPassword.length() > 14) {
            tip.setText("不超过14位！");
            unValidFunction(tip);
        }

        //合法
        if (userPassword.length() != 0 && userPassword.length() <= 14) {
            validFunction(tip);
        }
    }


    //确认密码
    //链接ensure的keyType
    public void ensurePassword(KeyEvent keyEvent) {
        espd = ensure.getText().trim() + keyEvent.getCharacter().trim();
        if (!espd.equals(userPassword) || espd == null || espd.length() == 0) {
            esLb.setText("请保持一致！");
            unValidFunction(esLb);
        } else {
            validFunction(esLb);
        }
    }


    //注册并登陆
    //判断密码
    @FXML
    public void login() {
        if(flag&&userPassword!=null&&espd!=null){
            //提交用户信息至服务器
            Map<String, Object> map = new HashMap<>();
            map.put("username", userNameField.getText());
            map.put("password", password.getText());
            BanchoClient.SendRequest(RequestType.User_Register, map);
            BanchoClient.addCallback(this);

            //---------------------------跳转界面------------------------
            register.setText("loading……");
        }
    }

    @Override
    public void callback(Request request) {
        Platform.runLater(() -> {
            if (request.type == RequestType.User_LoginResult) {
                long uid = Long.parseLong(request.payload.get("result").toString());

                if (uid>0) {
                    BanchoClient.removeCallback(this);
                    BanchoClient.user.username = request.payload.get("username").toString();
                    BanchoClient.user.id = Long.parseLong(request.payload.get("result").toString());
                    theStageController.setStage("primaryWindows","registerWindows");

                    String message = "你的ID为：" + BanchoClient.user.id;
                    Alert alertWindow = new Alert(Alert.AlertType.INFORMATION, message);
                    alertWindow.setTitle("恭喜");
                    alertWindow.setHeaderText("注册成功！");
                    alertWindow.show();
                } else {
                    String message = "注册信息有误";
                    Alert alertWindow = new Alert(Alert.AlertType.INFORMATION, message);
                    alertWindow.setTitle("警告");
                    alertWindow.setHeaderText("注册失败");
                    alertWindow.show();
                }
            }
        });
    }
}
